package com.task.job.recharge.workflow;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import com.entity.Item;
import com.entity.Measuringpoint;
import com.entity.Recharge;
import com.interfaces.MeterDao;
import com.protocol.sentjson.JsonResult;
import com.protocol.sentjson.SocketData;
import com.protocolmeter.ProtocolMerterService;
import com.protocolterminal.ProtocolTerminalService;
import com.protocolterminal.base.Seq;
import com.recharge.srevice.RechargeService;

public class WorkflowSTS645_Recharge implements Workflow {

	// 下发开户命令-回抄命令
	private String workflow = "10-0000-0100-03-070102FF-11;10-0000-0100-11-0333FF01-11";

	private String terminaladdress;
	private String terminalprotocol;
	private String meteraddress;
	private String meterprotocol;
	private RechargeService rechargeService;
	private Measuringpoint measuringpoint;
	private String keys;
	private MeterDao meterDao;

	public WorkflowSTS645_Recharge(String terminaladdress, String terminalprotocol, String meteraddress,
			String meterprotocol, Measuringpoint measuringpoint, RechargeService rechargeService, MeterDao meterDao,
			String keys) {
		this.terminaladdress = terminaladdress;
		this.terminalprotocol = terminalprotocol;
		this.meteraddress = meteraddress;
		this.meterprotocol = meterprotocol;
		this.measuringpoint = measuringpoint;
		this.rechargeService = rechargeService;
		this.keys = keys;
		this.meterDao = meterDao;
	}

	@Override
	public void Doflow(Recharge recharge) {

		List<Recharge> recharges = new ArrayList<>();
		recharge.setOptstatus("3");
		recharges.add(recharge);
		rechargeService.updateRecharge(recharges);

		List<Item> items = new ArrayList<>();

		String[] flows = this.workflow.split(";");

		for (String flow : flows) {
			String[] flowdata = flow.split("-");

			Item item = new Item();
			item.setAfn(flowdata[0]);
			item.setDa(flowdata[1]);
			item.setDt(flowdata[2]);
			item.setMetercontrol(flowdata[3]);
			item.setIdentification(flowdata[4]);
			item.setPRM(Integer.valueOf(flowdata[5]));

			items.add(item);
		}

		/*
		 * 执行数据流内容
		 */
		// 下发充值
		{
			SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			DecimalFormat decimalFormat = new DecimalFormat("#0.00");
			String money = decimalFormat.format(recharge.getMoney());
			money = money.replace(".", "");

			ProtocolMerterService protocolMerterService = new ProtocolMerterService();
			String frame645 = protocolMerterService.Encode(Integer.valueOf(meterprotocol), meteraddress,
					items.get(0).getMetercontrol(), items.get(0).getIdentification(), "00000000",
					money + "-" + recharge.getFrequency() + "-" + recharge.getCustomeraccount(), "00000000", keys);

			String datas = measuringpoint.getMeasuringpointport() + "-" + measuringpoint.getMeasuringpointbaud()
					+ "-0-1-0-8-200-0-100-" + frame645;

			ProtocolTerminalService protocolTerminalService = new ProtocolTerminalService();
			String sentframe = protocolTerminalService.Encode(Integer.valueOf(terminalprotocol), "10",
					new Seq(0, 1, 1, 1, 0).toString(), Arrays.asList("0000".split("-")),
					Arrays.asList("0100".split("-")), Arrays.asList(datas.split(";")), "", 1, 11, terminaladdress);
			// 发送
			String returndata = sent(String.valueOf(recharge.getRechargeid()), terminaladdress, false, sentframe);
			// 解析
			if (returndata != null && !returndata.equals("")) {
				String decodedata = protocolTerminalService.Decode(Integer.valueOf(terminalprotocol), sentframe,
						returndata);
				if (decodedata != null && !decodedata.equals("")) {
					String decodeframe645 = protocolMerterService.Decode(Integer.valueOf(meterprotocol), frame645,
							decodedata);
					// 验证是否成
					String[] resultdata = decodeframe645.split("-");
					if (resultdata.length == 2 && resultdata[1].equalsIgnoreCase("成功")) {
						// 修改记录
						recharge.setOptstatus("1");
						recharge.setRechargetime(dateFormater.format(new Date().getTime()));
						recharge.setOptnum(recharge.getOptnum() + 1);
					} else {
						returnfalse(recharge, dateFormater, resultdata[1]);
					}
				} else {
					returnfalse(recharge, dateFormater, "解析失败");
				}
			} else {
				returnfalse(recharge, dateFormater, "无返回数据");
			}
		}

		// 读取充值记录
		{
			SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			DecimalFormat decimalFormat = new DecimalFormat("#0.00");
			String money = decimalFormat.format(recharge.getMoney());
			money = money.replace(".", "");

			ProtocolMerterService protocolMerterService = new ProtocolMerterService();
			String frame645 = protocolMerterService.Encode(Integer.valueOf(meterprotocol), meteraddress,
					items.get(1).getMetercontrol(), items.get(1).getIdentification(), "00000000",
					money + "-" + recharge.getFrequency() + "-" + recharge.getCustomeraccount(), "00000000", keys);

			String datas = measuringpoint.getMeasuringpointport() + "-" + measuringpoint.getMeasuringpointbaud()
					+ "-0-1-0-8-200-0-100-" + frame645;

			ProtocolTerminalService protocolTerminalService = new ProtocolTerminalService();
			String sentframe = protocolTerminalService.Encode(Integer.valueOf(terminalprotocol), "10",
					new Seq(0, 1, 1, 1, 0).toString(), Arrays.asList("0000".split("-")),
					Arrays.asList("0100".split("-")), Arrays.asList(datas.split(";")), "", 1, 11, terminaladdress);
			// 发送
			String returndata = sent(String.valueOf(recharge.getRechargeid()), terminaladdress, true, sentframe);
			// 解析
			if (returndata != null && !returndata.equals("")) {
				String decodedata = protocolTerminalService.Decode(Integer.valueOf(terminalprotocol), sentframe,
						returndata);
				if (decodedata != null && !decodedata.equals("")) {
					String decodeframe645 = protocolMerterService.Decode(Integer.valueOf(meterprotocol), frame645,
							decodedata);
					// 验证是否成
					String[] resultdata = decodeframe645.split("-");
					if (resultdata.length == 2 && !resultdata[1].equalsIgnoreCase("")) {
						// 保存充值金额
						Double money1 = Double.valueOf(resultdata[1].substring(0, 8)) / 100;
						Double money2 = Double.valueOf(resultdata[1].substring(8, 16)) / 100;
						Double money3 = Double.valueOf(resultdata[1].substring(16, 24)) / 100;

						recharge.setBeforemoney(money3);
						recharge.setAftermoney(money2);
						recharge.setTotalmoney(money1);
						recharge.setRemark("");

						meterDao.updateMetermoney(money2, measuringpoint.getMeterid());
					} else {
						returnfalse(recharge, dateFormater, resultdata[1]);
					}
				} else {
					returnfalse(recharge, dateFormater, "解析失败");
				}
			} else {
				returnfalse(recharge, dateFormater, "无返回数据");
			}
		}
		recharge.setOptnum(recharge.getOptnum() + 1);

		List<Recharge> rechargesreturn = new ArrayList<>();
		rechargesreturn.add(recharge);
		rechargeService.updateRecharge(rechargesreturn);

	}

	private void returnfalse(Recharge recharge, SimpleDateFormat dateFormater, String message) {
		// 修改记录
		if (recharge.getOptnum() > 3) {
			recharge.setOptstatus("2");
			recharge.setRechargetime(dateFormater.format(new Date().getTime()));
		} else {
			// 修改记录
			recharge.setOptstatus("0");
			recharge.setRechargetime(dateFormater.format(new Date().getTime()));
		}
		recharge.setRemark(message);
	}

	private String sent(String taskid, String terminaladdress, boolean last, String sentframe) {
		// http请求
		String urlsent = "http://localhost:8000/SocketControl/sent/task";
		RestTemplate restTemplatesent = new RestTemplate();

		// 组发送内容
		JsonResult<SocketData> sentjson = new JsonResult<>();

		SocketData socketData = new SocketData();
		socketData.setTaskid(taskid);
		socketData.setTerminaladdress(terminaladdress);
		socketData.setMessage(sentframe);
		socketData.setLast(last);
		sentjson.setData(socketData);

		// 发送
		@SuppressWarnings("rawtypes")
		ResponseEntity<JsonResult> returnjson = restTemplatesent.postForEntity(urlsent, sentjson, JsonResult.class);
		// 终端不在线，终端通讯中
		if (returnjson.getBody().getState() == 3002 || returnjson.getBody().getState() == 3003) {
			return null;
		}

		// 准备接收
		Date date1 = new Date();
		Date date2 = new Date();

		boolean flag = false;

		String urlback = "http://localhost:8000/SocketControl/receive/task";
		RestTemplate restTemplatereceive = new RestTemplate();

		String returndata = null;
		while (((date2.getTime() - date1.getTime()) < 2 * 60 * 1000) && !flag) {
			@SuppressWarnings("rawtypes")
			ResponseEntity<JsonResult> receiveresult = restTemplatereceive.postForEntity(urlback, sentjson,
					JsonResult.class);
			// 正常返回
			if (receiveresult.getBody().getState() == 3100) {
				@SuppressWarnings("unchecked")
				Map<String, String> map = (Map<String, String>) receiveresult.getBody().getData();

				returndata = map.get("message");
				if (!returndata.equals("")) {
					flag = true;
				}
			}

			try {
				Thread.sleep(1 * 1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			date2 = new Date();
		}
		return returndata;
	}

}
